package pile.customer.config;




import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.crypto.KmsEncryptionMaterials;
import freemarker.template.utility.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pile.customer.params.ReceivingInformation;
import pile.customer.service.ICustomerServiceInformationService;


import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/customerServiceWebSocket/{uId}")
@Slf4j
public class CustomerServiceWebSocketServerUtil {

    private Session session;
    private static CopyOnWriteArraySet<CustomerServiceWebSocketServerUtil> webSocketSet = new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<String, CustomerServiceWebSocketServerUtil> webSocketMap  = new ConcurrentHashMap<>();
    private String uId = null;


    private static ICustomerServiceInformationService customerServiceInformationService ;

    @Autowired
    private ICustomerServiceInformationService autowiredCustomerServiceInformationService;

    @PostConstruct
    public void init() {
        customerServiceInformationService = autowiredCustomerServiceInformationService;
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("uId") String uId){
        this.session = session;
        this.uId = uId;
        if(webSocketMap .containsKey(uId)){

            //客服已在线
            ReceivingInformation receivingInformation = new ReceivingInformation();

            receivingInformation.setCode(401);
            receivingInformation.setMessage("客服已在线,请重新登录");
            sendInfo(JSON.toJSONString(receivingInformation),uId);

           /* webSocketMap .remove(uId);
            webSocketMap .put(uId,this);*/
        }else{
            webSocketMap .put(uId,this);
            webSocketSet.add(this);
        }

        log.info("【websocket消息】有新客服的连接，客服id:"+uId+"总数：{}",webSocketMap.size());
    }

    @OnClose
    public void onClose(){
        if(webSocketMap.containsKey(uId)){
            webSocketMap.remove(uId);
            //从set中删除
            webSocketSet.remove(this);
        }
        log.info("【websocket消息】客服连接断开，总数：{}",webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message){


        JSONObject jsonObject = JSON.parseObject(message);

        String messageStr =  jsonObject.getString("message");

        String openId =  jsonObject.getString("openId");
        String customerServiceAccount = jsonObject.getString("customerServiceAccount");
        String channel = jsonObject.getString("channel");
        //消息类型
        String messageType = jsonObject.getString("messageType");



        log.info("【websocket消息】收到客服客户端发来的消息：{}",message);

        ReceivingInformation receivingInformation = new ReceivingInformation();

        receivingInformation.setMessage(messageStr);
        receivingInformation.setOpenId(openId);
        receivingInformation.setCustomerServiceAccount(customerServiceAccount);
        //发送时间
        receivingInformation.setSendingTime(new Date());
        //渠道
        if(StringUtils.isEmpty(channel)){
            channel = "1";
        }
        if(StringUtils.isEmpty(messageType)){
            messageType = "1";
        }
        receivingInformation.setChannel(Integer.valueOf(channel));
        receivingInformation.setMessageType(Integer.valueOf(messageType));
        customerServiceInformationService.processingMessages(receivingInformation);
    }

    public void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送自定义消息
     * */
    public  void sendInfo(String message,String uId)   {

        //log.info("发送消息到:"+uId+"，报文:"+message);
            if(uId==null){
                uId = "null";
            }

            //判断客服是否存在 不存在 不发送消息

            if(webSocketMap.containsKey(uId)){
                webSocketMap.get(uId).sendMessage(message);
            }else{
                log.warn("客服不在线，由用户发送消息:"+ message);
            }
    }


    /**
     *
     * */
    public  List<String>  getOnlineList() {

        List<String> onlineUsers = new ArrayList<>();
        for (String userId : webSocketMap.keySet()) {
            onlineUsers.add(userId);
        }
        return onlineUsers;

    }

    public boolean isOnLine(String uId) {
        return webSocketMap.containsKey(uId);
    }


    public void offline(String uId){
        if(webSocketMap.containsKey(uId)){
            webSocketMap.remove(uId);
            //从set中删除
            webSocketSet.remove(this);
        }
        log.info("【websocket消息】客服连接断开，总数：{}",webSocketSet.size());
    }


}
